package io.jee.runshan.utils;

import io.jee.medusa.remote.RemoteConnector;
import io.jee.runshan.domain.remote.weishequ.AppToken;

import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeiShequConstant {
	private static final String WeishequPropertiesFile = "weishequ.properties";
	private static Logger logger = LoggerFactory.getLogger(WeiShequConstant.class);

	/**
	 * 最新的Token
	 */
	private static String AccessToken;
	/**
	 * 最后一次获取Token的时间（毫秒）
	 */
	private static long AccessTokenGeted = 0L;
	/**
	 * 最后一次Token的有效时间（毫秒）
	 */
	private static long AccessTokenExpiresIn = 0L;

	private static Map<String, String> property = null;

	/**
	 * 获取Token
	 * @Created: 2015年2月6日
	 * @Last_modified: 2015年2月6日 下午7:11:18
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @return
	 */
	public static String getApptoken() {
		long currentTime = new Date().getTime();
		Long time = currentTime / 1000;
		if (currentTime - AccessTokenExpiresIn > AccessTokenGeted) {
			String appid = getProperty("appid");
			String appSecret = getProperty("appSecret");
			String sig = SHACoder.encode(appid + appSecret + time);
			String url = getProperty("appTokenUrl") + "?appId=" + appid + "&sig=" + sig + "&time=" + time + "&type=security";
			AppToken token = RemoteConnector.get(url, null, AppToken.class);
			AccessToken = token.getData().getAppToken();
			AccessTokenExpiresIn = token.getData().getExpires();
			AccessTokenGeted = currentTime;
		}
		return AccessToken;
	}
	
	/**
	 * 参数RFC1738编码
	 * @Created: 2015年2月6日
	 * @Last_modified: 2015年2月6日 下午7:48:34
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param param
	 * @return
	 */
	public static String paramEncoder(String param) {
		String result = "";
		try {
			if (StringUtils.notBlank(param)) {
				result = URLEncoder.encode(param, "UTF-8");
			}
		} catch (Exception e) {}
		return result;
	}

	public static String getProperty(String key) {
		if (property == null) {
			property = PropertiesUtils.toMap(PropertiesUtils.loadProperties(WeishequPropertiesFile));
			logger.debug("load WeiShequ Properties File Success!!!");
		}
		return property.get(key);
	}

	public static String getProperty(int key) {
		return getProperty(String.valueOf(key));
	}
}
